package com.xgl.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xgl.pojo.*;
import com.xgl.service.*;
import com.xgl.utils.Md5Utils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生处罚信息 前端控制器
 * </p>
 *
 * @author 最最帅气的熊国林
 * @since 2021-05-09
 */
@RestController
@RequestMapping("/student/punish")
public class PunishmentinfoController {
    @Autowired
    private IPunishmentinfoService iPunishmentinfoService;
    @Autowired
    private IDepartmentService iDepartmentService;
    @Autowired
    private IMajorService iMajorService;
    @Autowired
    private INationService iNationService;


    @ApiOperation(value = "生成学生惩处信息hash")
    @GetMapping("compute/{id}")
    public String computeHash(@PathVariable Integer id) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        List<Punishmentinfo> list = iPunishmentinfoService.getPunishmentinfo(id);
        Map<String,String> map = new HashMap<String,String>();
        list.forEach(studentinfo -> {
            map.put("s_number",studentinfo.getS_number().toString());
            map.put("name",studentinfo.getName().toString());
            map.put("nationId",studentinfo.getNationId().toString());
            map.put("sex",studentinfo.getSex().toString());
            map.put("grade",studentinfo.getGrade().toString());
            map.put("s_level",studentinfo.getS_level().toString());
            map.put("s_category",studentinfo.getS_category().toString());
            map.put("departmentId",studentinfo.getDepartmentId().toString());
            map.put("majorId",studentinfo.getMajorId().toString());
            map.put("id",studentinfo.getId().toString());
            map.put("punishment_info",studentinfo.getPunishment_info().toString());
            map.put("punishment_type",studentinfo.getPunishment_type().toString());
            map.put("punishment_time",studentinfo.getPunishment_time().toString());
            map.put("punishment_department",studentinfo.getPunishment_department().toString());

        });

        String hashCode = Md5Utils.SHA256(
                map.get("id")+ map.get("s_number")
                + map.get("name")+ map.get("nationId")
                + map.get("grade") + map.get("sex")
                + map.get("majorId") + map.get("departmentId")
                + map.get("s_level") + map.get("s_category")
                + map.get("punishment_info") + map.get("punishment_type")
                + map.get("punishment_time") + map.get("punishment_department")
        );
        //System.out.println("test is " + test);

        iPunishmentinfoService.insertHashCode(id,hashCode);
        return hashCode;
    }

    @ApiOperation(value = "获取所有学生惩处信息（分页）")
    @GetMapping("/")
    public RespPageBean getPunishmentinfoByPage(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer size,
                                            Punishmentinfo punishmentinfo, LocalDate[] beginDateScope){
        return iPunishmentinfoService.getPunishmentinfoByPage(currentPage,size,punishmentinfo,beginDateScope);
    }

    @ApiOperation(value = "增加学生惩处信息")
    @PostMapping("/")
    public RespBean addPunishmentinfo(@RequestBody Punishmentinfo punishmentinfo){
        return iPunishmentinfoService.addPunishmentinfo(punishmentinfo);
    }

    @ApiOperation(value = "更新学生惩处信息")
    @PutMapping("/")
    public RespBean updatePunishmentinfo(@RequestBody Punishmentinfo punishmentinfo){
        if (iPunishmentinfoService.updateById(punishmentinfo)){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation(value = "删除学生惩处信息")
    @DeleteMapping("/{id}")
    public RespBean deletePunishmentinfo(@PathVariable Integer id){
        if (iPunishmentinfoService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nation")
    public List<Nation> getAllNation(){
        return iNationService.list();
    }

    @ApiOperation(value = "获取所有专业")
    @GetMapping("/major")
    public List<Major> getAllPosition(){
        return iMajorService.list();
    }

    @ApiOperation(value = "获取所有学院")
    @GetMapping("/department")
    public List<Department> getAllDepartment(){
        return iDepartmentService.list();
    }

    @ApiOperation(value = "导出学生惩处数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportPunishmentinfo(HttpServletResponse response){
        List<Punishmentinfo> list = iPunishmentinfoService.getPunishmentinfo(null);
        ExportParams params = new ExportParams("学生惩处信息表","学生惩处信息表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params,Punishmentinfo.class,list);
        //输出
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type","application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("学生惩处信息表.xls","UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null != outputStream){
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "导入学生惩处数据")
    @ApiImplicitParams({@ApiImplicitParam(name="file",value = "上传文件",dataType = "MultipartFile")})
    @PostMapping("/import")
    public RespBean importPunishmentinfo(MultipartFile file){
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);
        List<Nation> nations = iNationService.list();
        List<Major> majors = iMajorService.list();
        List<Department> departments = iDepartmentService.list();
        try {
            List<Punishmentinfo> list = ExcelImportUtil.importExcel(file.getInputStream(), Punishmentinfo.class, params);
            list.forEach(punishmentinfo ->{
                //民族id
                punishmentinfo.setNationId(nations.get(nations.indexOf(new Nation(punishmentinfo.getNation().getName()))).getId());
                //专业id
                punishmentinfo.setMajorId(majors.get(majors.indexOf(new Major(punishmentinfo.getMajor().getName()))).getId());
                //学院id
                punishmentinfo.setDepartmentId(departments.get(departments.indexOf(new Department(punishmentinfo.getDepartment().getName()))).getId());
                //职称id

            });
            if (iPunishmentinfoService.saveBatch(list)){
                return RespBean.success("导入成功");
            }
            return RespBean.error("导入失败");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }

}
